package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationDTO;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Double latitude, Double longitude, String address, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        boolean exists = mongoTemplate.exists(query, UserLocation.class);
        if (!exists) {
            //新增
            UserLocation location = new UserLocation();
            location.setUserId(userId);
            location.setAddress(address);
            location.setUpdated(System.currentTimeMillis());
            location.setLastUpdated(System.currentTimeMillis());
            location.setId(ObjectId.get());
            location.setCreated(System.currentTimeMillis());
            location.setLocation(new GeoJsonPoint(longitude, latitude));
            mongoTemplate.save(location);
        } else {
            //修改
            GeoJsonPoint point = new GeoJsonPoint(longitude, latitude);
            Update update = new Update();
            update.set("address", address)
                    .set("location", point)
                    .set("updated", System.currentTimeMillis());
            mongoTemplate.updateFirst(query, update, UserLocation.class);
        }


    }

    @Override
    public List<UserLocationDTO> searchNear(Long userId, Integer metre) {
        //1. 查询用户的位置
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.limit(1);
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        //2. 以用户为圆点画圆
        GeoJsonPoint point = userLocation.getLocation();
        Distance distance = new Distance(metre / 1000, Metrics.KILOMETERS);
        Circle circle = new Circle(point, distance);
        //3. 搜索指定范围内的人
        Query queryNear = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(queryNear, UserLocation.class);

        return UserLocationDTO.translateList(userLocations);
    }
}
